from flask import Blueprint, jsonify, request, make_response, session
import redis, random, time
from ..utils.sendMessage import sendSMS
from ..utils.genereate_code import get_verify_code
from ..extensions import pool, jys_db, wallet_db
from ..utils.hash_passwd import hash
from ..utils.token import gen_token, check_activate_token
from io import BytesIO
from ..utils.validation import checkPasswd, phone_validatte
from ..utils.generate_invit_code import generate_invit_code

users = Blueprint('users', __name__)


# 红包
@users.route('/invit/', methods=['POST'])
def index():
    invit = request.form.get('invit')
    res = jys_db.selectone('select username from bf_user where invit="%s"' % invit)
    if res:
        result_json = jsonify({"code": 1, "data": {'invit': invit, "username": res["username"]}, "msg": "成功"})
    else:
        result_json = jsonify({"code": 0, "msg": "未找到该邀请码对应的用户", "data": ""})
    return result_json


# 短信验证码
@users.route('/send_verify_sms/', methods=['POST'])
def send_verify_sms():
    # 获取手机号码
    phoneNumber = request.form.get('phone')
    if not phoneNumber:
        return jsonify({'code': 0, 'data': '', 'msg': '请输入手机号码'})
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 从连接池中获取redis
    redis_store = redis.Redis(connection_pool=pool)
    # 连接数据库
    sql = 'select id from bf_user where mobile=%d' % int(phoneNumber)
    res = jys_db.selectone(sql)
    if res:
        return jsonify({'code': 0, 'data': '', 'msg': '该手机号已经注册'})

    requestCount = redis_store.get('validateCount:%s' % phoneNumber)
    if not requestCount:
        requestCount = 0
    else:
        requestCount = int(requestCount)
    if requestCount > 9:
        return jsonify({'code': 0, 'msg': '当日请求次数过多,请明日再试!', 'data': ''})
    # 当 key 不存在时，返回 -2 。 当 key 存在但没有设置剩余生存时间时，返回 -1 。 否则，以毫秒为单位，返回 key 的剩余生存时间。
    ttlstime = redis_store.ttl('validateCode:%s' % phoneNumber)
    if ttlstime:
        if ttlstime > 0:
            return jsonify({'code': 0, 'data': {'ttlstime': ttlstime}, 'msg': '请等待 %d 秒后重试' % ttlstime})
    # 验证码
    validate_number = str(random.randint(100000, 1000000))
    result, resMsg = sendSMS(phoneNumber, '您好，您的验证码是：%s【coinwin】,,验证码10分钟内有效,请输入验证码,完成手机验证' % (str(validate_number)))
    # 发送验证码失败
    if not result:
        return jsonify({'code': 0, 'data': '', 'msg': '发送验证码失败'})
    else:
        '''
        pipeline可以批量请求redis,大大提升了性能
        '''
        # 发送成功后 redis记录相应数据
        pipeline = redis_store.pipeline()
        # 请求次数记录时间为1天
        pipeline.set('validateCount:%s' % phoneNumber, int(requestCount) + 1)
        pipeline.expire('validateCount:%s' % phoneNumber, 60 * 60 * 24)
        # 请求验证码的有效时间为1分钟
        pipeline.set('validateCode:%s' % phoneNumber, validate_number)
        pipeline.expire('validateCode:%s' % phoneNumber, 60 * 10)
        # 执行所有的命令
        pipeline.execute()
        ttlstime = redis_store.ttl('validateCode:%s' % phoneNumber)
        return jsonify({'code': 1, 'msg': '发送验证码成功', 'data': {'ttlstime': ttlstime}})


# 短信验证码(忘记密码,登录使用)
@users.route('/send_verify_sms_for_password/', methods=['POST'])
def send_verify_sms_for_password():
    # 获取手机号码
    phoneNumber = request.form.get('phone')
    if not phoneNumber:
        return jsonify({'code': 0, 'data': '', 'msg': '请输入手机号码'})
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 从连接池中获取redis
    redis_store = redis.Redis(connection_pool=pool)
    pipeline = redis_store.pipeline()
    # 连接数据库
    res = jys_db.selectone('select id from bf_user where mobile=%d' % int(phoneNumber))
    if not res:
        return jsonify({'code': 0, 'data': '', 'msg': '该手机号没有注册'})
    requestCount = redis_store.get('validateCount2:%s' % phoneNumber)
    if not requestCount:
        requestCount = 0
    else:
        requestCount = int(requestCount)
    if requestCount > 9:
        return jsonify({'code': 0, 'msg': '当日请求次数过多,请明日再试!', 'data': ''})
    # 当 key 不存在时，返回 -2 。 当 key 存在但没有设置剩余生存时间时，返回 -1 。 否则，以毫秒为单位，返回 key 的剩余生存时间。
    ttlstime = redis_store.ttl('validateCode2:%s' % phoneNumber)
    if ttlstime:
        if ttlstime > 0:
            return jsonify({'code': 0, 'data': {'ttlstime': ttlstime}, 'msg': '请等待 %d 秒后重试' % ttlstime})
    # 验证码
    validate_number = str(random.randint(100000, 1000000))
    result, resMsg = sendSMS(phoneNumber, '您好，您的验证码是：%s【coinwin】,验证码10分钟内有效,请输入验证码,完成手机验证' % (str(validate_number)))
    # 发送验证码失败
    if not result:
        return jsonify({'code': 0, 'data': resMsg, 'msg': '发送验证码失败'})
    else:
        '''
        pipeline可以批量请求redis,大大提升了性能
        '''
        # 发送成功后 redis记录相应数据
        # 请求次数记录时间为1天
        pipeline.set('validateCount2:%s' % phoneNumber, int(requestCount) + 1)
        pipeline.expire('validateCount2:%s' % phoneNumber, 60 * 60 * 24)
        # 请求验证码的有效时间为1分钟
        pipeline.set('validateCode2:%s' % phoneNumber, validate_number)
        pipeline.expire('validateCode2:%s' % phoneNumber, 60 * 10)
        # 执行所有的命令
        pipeline.execute()
        return jsonify({'code': 1, 'msg': '发送验证码成功', 'data': {'ttlstime': ttlstime}})


# 手机注册
@users.route('/add/', methods=['GET', 'POST'])
def add():
    # 获取用户名,验证码,手机号码,密码, 邀请码(选填)
    invit = request.form.get('invit',type=str,default='')
    username = request.form.get('username')
    validate_number = request.form.get('validate_number')
    phoneNumber = request.form.get('phone')
    passwd = request.form.get('passwd')
    if not username or not validate_number or not phoneNumber or not passwd:
        return jsonify({'code': 0, 'data': '', 'msg': '数据不能为空'})
    # 检查手机号
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 检查密码
    res, msg = checkPasswd().check(passwd)
    if not res:
        return jsonify({'code': 0, 'data': '', 'msg': msg})
    # 检查手机号是否注册
    res = jys_db.selectone('select id from bf_user where mobile=%d' % int(phoneNumber))
    if res:
        return jsonify({'code': 0, 'data': '', 'msg': '该手机号已经注册'})
    # 检查用户名是否存在
    print(jys_db.selectone("select id from jys.bf_user where username='%s'" % username))
    if jys_db.selectone("select id from jys.bf_user where username='%s'" % username):
        print(11111)
        return jsonify({'code': 0, 'data': '', 'msg': '该用户名已经被使用'})
    # 检查是否发送过验证码
    redis_store = redis.Redis(connection_pool=pool)
    validate_number_in_redis = redis_store.get('validateCode:%s' % phoneNumber)
    if not validate_number_in_redis:
        return jsonify({'code': 0, 'data': '', 'msg': '请先发送验证码!'})
    # 检查验证码是否过时
    ttlstime = redis_store.ttl('validateCode:%s' % phoneNumber)
    if ttlstime == -2:
        return jsonify({'code': 0, 'data': '', 'msg': '验证码已失效'})
    # 检查验证码是否正确
    if validate_number.upper() != validate_number_in_redis.decode('utf-8').upper():
        return jsonify({'code': 0, 'data': '', 'msg': '验证码错误'})
    #是否有邀请码，没有为原始码
    if not invit:
        invit_1 = 0
        invit_2 = 0
        invit_3 = 0
    else:
        sql = 'select id,invit_1,invit_2,invit_3 from bfuser where invit={}'.format(invit)
        result = jys_db.selectone(sql)
        #邀请码输入错误
        if not result:
            return jsonify({'code': 0, 'data': '', 'msg': '该邀请码输入错误'})
        #已经是三级邀请
        if result['invit_3'] != 0:
            return jsonify({'code': 0, 'data': '', 'msg': '该邀请码已是三级邀请，请直接注册'})
        invit_1 = result['id']
        invit_2 = result['invit_1']
        invit_3 = result['invit_2']
    # 哈希密码
    passwd = hash(passwd)
    t = int(time.time())
    # 为用户生成邀请码
    invit_code = generate_invit_code()
    # 数据库插入用户信息
    sql = 'insert into bf_user(username,mobile,mobiletime,`password`,invit,enname,status,addtime,invit_1,invit_2,invit_3) VALUES("%s","%s",%d,"%s","%s","%s",1,%d,%d,%d,%d);' % (
        str(phoneNumber), str(phoneNumber), t, passwd, invit_code, username, t,invit_1,invit_2,invit_3)
    jys_db.execute(sql)
    # 获取用户id
    res = jys_db.selectone('select * from bf_user where mobile=%d' % int(phoneNumber))
    user_id = res['id']
    # 为用户找到可以分配的BTC地址
    btc_pubadd = wallet_db.selectone('select id,pubadd from wallet.btc_user where user_id is NULL and status=1;')[
        'pubadd']
    # 申明该BTC地址的拥有权
    wallet_db.execute('update wallet.btc_user set user_id=%d,status=0 where id=%d' % (user_id, res["id"]))
    # 为用户找到可以分配的ETH地址
    eth_pubadd = wallet_db.selectone('select id,pubadd from wallet.eth_user where user_id is NULL and status=1;')[
        'pubadd']
    # 申明该ETH地址的拥有权
    wallet_db.execute('update wallet.eth_user set user_id=%d,status=0 where id=%d' % (user_id, res["id"]))
    # 绑定bf_user(用户)与bf_user_coin(资金)
    sql = 'insert into bf_user_coin(userid,btc,btcd,btcb,eth,ethd,ethb,ltc,ltcd,ltcb,cusd,cusdd,usdt,usdtd,usdtb,bch,bchd,bchb) values(%d,0.0003,0,"%s",0,0,"%s",0,0,"",0,0,0,0,"",0,0,"")' % (
        user_id, btc_pubadd, eth_pubadd)
    jys_db.execute(sql)
    # 邀请码存在,将邀请人和用户存入邀请表
    if invit:
        # 获取邀请人id
        invit_id = jys_db.selectone('select id from bf_user where invit="%s"' % invit)["id"]
        if res:
            jys_db.execute('insert into bf_invit(userid,invit) values(%d,%d)' % (invit_id, user_id))
    # 删除验证码
    result_json = jsonify({'code': 1, 'data': '', 'msg': '注册成功'})
    resp = make_response(result_json)
    # 设置cookie过期时间
    token = gen_token(res['id'])
    expires = time.time() + 60 * 60 * 24 * 31
    resp.set_cookie('token', token, expires=expires)
    session['id'] = res['id']
    session['username'] = res['username']
    session['mobile'] = res['mobile']
    redis_store.delete('validateCode:%s' % phoneNumber)
    return resp


# 苹果手机注册
@users.route('/add_for_iphone/', methods=['GET', 'POST'])
def add_for_iphone():
    # 获取用户名,验证码,手机号码,密码, 邀请码(选填)
    invit = request.form.get('invit')
    username = request.form.get('username')
    validate_number = request.form.get('validate_number')
    phoneNumber = request.form.get('phone')
    passwd = request.form.get('passwd')
    if not username or not validate_number or not phoneNumber or not passwd:
        return jsonify({'code': 0, 'data': '', 'msg': '数据不能为空'})
    # 检查手机号
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 检查密码
    res, msg = checkPasswd().check(passwd)
    if not res:
        return jsonify({'code': 0, 'data': '', 'msg': msg})
    # 检查手机号是否注册
    res = jys_db.selectone('select id from bf_user where mobile=%d' % int(phoneNumber))
    if res:
        return jsonify({'code': 0, 'data': '', 'msg': '该手机号已经注册'})
    # 检查用户名是否存在
    print(jys_db.selectone("select id from jys.bf_user where username='%s'" % username))
    if jys_db.selectone("select id from jys.bf_user where username='%s'" % username):
        print(11111)
        return jsonify({'code': 0, 'data': '', 'msg': '该用户名已经被使用'})
    # 检查是否发送过验证码
    redis_store = redis.Redis(connection_pool=pool)
    validate_number_in_redis = redis_store.get('validateCode:%s' % phoneNumber)
    if not validate_number_in_redis:
        return jsonify({'code': 0, 'data': '', 'msg': '请先发送验证码!'})
    # 检查验证码是否过时
    ttlstime = redis_store.ttl('validateCode:%s' % phoneNumber)
    if ttlstime == -2:
        return jsonify({'code': 0, 'data': '', 'msg': '验证码已失效'})
    # 检查验证码是否正确
    if validate_number.upper() != validate_number_in_redis.decode('utf-8').upper():
        return jsonify({'code': 0, 'data': '', 'msg': '验证码错误'})
    # 哈希密码
    passwd = hash(passwd)
    t = int(time.time())
    # 为用户生成邀请码
    invit_code = generate_invit_code()
    # 数据库插入用户信息
    sql = 'insert into bf_user(username,mobile,mobiletime,`password`,invit) VALUES("%s",%d,%d,"%s","%s");' % (
        username, int(phoneNumber), t, passwd, invit_code)
    jys_db.execute(sql)
    # 获取用户id
    res = jys_db.selectone('select * from bf_user where mobile=%d' % int(phoneNumber))
    user_id = res['id']
    # 为用户找到可以分配的BTC地址
    btc_pubadd = wallet_db.selectone('select id,pubadd from wallet.btc_user where user_id is NULL and status=1;')[
        'pubadd']
    # 申明该BTC地址的拥有权
    wallet_db.execute('update wallet.btc_user set user_id=%d,status=0 where id=%d' % (user_id, res["id"]))
    # 为用户找到可以分配的ETH地址
    eth_pubadd = wallet_db.selectone('select id,pubadd from wallet.eth_user where user_id is NULL and status=1;')[
        'pubadd']
    # 申明该ETH地址的拥有权
    wallet_db.execute('update wallet.eth_user set user_id=%d,status=0 where id=%d' % (user_id, res["id"]))
    # 绑定bf_user(用户)与bf_user_coin(资金)
    jys_db.execute(
        'insert into bf_user_coin(userid,btc,btcd,btcb,eth,ethd,ethb) values(%d,0.0003,0,"%s",0.0003,0,"%s")' % (
            user_id, btc_pubadd, eth_pubadd))
    # 邀请码存在,将邀请人和用户存入邀请表
    if invit:
        # 获取邀请人id
        invit_id = jys_db.selectone('select id from bf_user where invit="%s"' % invit)["id"]
        if res:
            jys_db.execute('insert into bf_invit(userid,invit) values(%d,%d)' % (invit_id, user_id))
    # 删除验证码
    return jsonify({'code': 1, 'data': '', 'msg': '注册成功'})


# 图片验证码验证
@users.route('/validate_code/', methods=['POST'])
def validate_code():
    image = session.get('image')
    if not image:
        return jsonify({'code': 1, 'msg': '验证码已切换', 'data': ''})
    requestCount = image.get('verify_count')
    # 检查请求次数是否大于5
    if requestCount > 5:
        return jsonify({'code': 0, 'msg': '请求次数过多,请休息一下再试!', 'data': ''})
    else:
        return jsonify({'code': 1, 'msg': '验证码已切换', 'data': ''})


# 图形验证码
@users.route('/code/')
def get_code():
    # 获取手机号码
    image, code = get_verify_code()
    # 图片以二进制形式写入
    buf = BytesIO()
    image.save(buf, 'jpeg')
    buf_str = buf.getvalue()
    # 把buf_str作为response返回前端，并设置首部字段
    resp = make_response(buf_str)
    resp.headers['Content-Type'] = 'image/gif'
    # 发送成功后 redis记录相应数据
    redis_store = redis.Redis(connection_pool=pool)
    pipeline = redis_store.pipeline()
    # 获取验证码的请求次数
    requestCount = 0
    image = session.get('image', None)
    if image:
        requestCount = image.get('verify_count', 0)
    # 请求次数加1
    # session['verify_code']=code
    session['image'] = {"verify_code": code, "verify_count": int(requestCount) + 1,
                        "verify_time": int(time.time()) + 90}
    return resp


# 验证码登录
@users.route('/login/', methods=['POST'])
def login():
    print(request.url)
    # 设置session过期时间
    session.permanent = True
    # 获取手机号码,密码,验证码
    phoneNumber = request.form.get('phone')
    passwd = request.form.get('passwd')
    validate_number = request.form.get('validate_number')
    # 检查数据是否为空
    if not validate_number or not phoneNumber or not passwd:
        return jsonify({'code': 0, 'data': '', 'msg': '数据不能为空'})
    # 检查手机号
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 检查图形验证码
    image = session.get('image')
    # 检查验证码是否有效
    if not image or image.get('verify_time') < time.time():
        return jsonify({'code': 0, 'data': '', 'msg': '验证码无效'})
    # 检查验证码是否正确
    code = image.get("verify_code")
    if code.upper() != validate_number.upper():
        return jsonify({'code': 0, 'data': '', 'msg': '验证码不正确'})
    # 检查该用户是否存在
    res = jys_db.selectone('select * from bf_user  where mobile=%d ' % int(phoneNumber))
    # 如果不存在
    if not res:
        return jsonify({'code': 0, 'data': {'token': 0}, 'msg': '用户名或密码错误'})
    # 检查密码的错误次数
    errPwdCount = session.get('errPwdCount')
    if not errPwdCount:
        errPwdCount = 0
    else:
        errPwdCount = int(errPwdCount)
    # 密码错误次数超过五次
    if errPwdCount > 5:
        return jsonify({'code': 0, 'msg': '账号因密码错误超过5次被冻结，请联系管理员解封', 'data': ''})
    # 检查密码是否错误
    if not hash(passwd) == res['password']:
        session['errPwdCount'] = errPwdCount + 1
        if 0 <= int(errPwdCount) <= 4:
            return jsonify({'code': 0, 'msg': '密码错误%d次,超过5次账号将被冻结!' % (int(errPwdCount) + 1), 'data': ''})
        else:
            try:
                jys_db.execute('update bf_user set status=0 where mobile=%d' % int(phoneNumber))
            except Exception as e:
                print(e)
            return jsonify({'code': 0, 'msg': '账号因密码错误超过5次被冻结，请联系管理员解封', 'data': ''})
    else:
        token = gen_token(res['id'])
        result_json = jsonify({'code': 1, 'data': '', 'msg': '登陆成功'})
        resp = make_response(result_json)
        # 更新登录时间
        t = int(time.time())
        sql = 'update df_user set `login_time`={} where id={};'.format(t, int(res['id']))
        jys_db.execute(sql)
        # 设置cookie过期时间
        expires = time.time() + 60 * 60 * 24 * 31
        resp.set_cookie('token', token, expires=expires)
        session['id'] = res['id']
        session['username'] = res['username']
        session['mobile'] = res['mobile']
        session.pop("image", None)
        return resp


# 手机登录
@users.route('/phone_login/', methods=['POST'])
def phone_login():
    # session过期时间
    session.permanent = True
    # 获取数据
    validate_number = request.form.get('validate_number')
    phoneNumber = request.form.get('phone')
    # 检查数据是否为空
    if not validate_number or not phoneNumber:
        return jsonify({'code': 0, 'data': '', 'msg': '数据不能为空'})
    # 检查手机号
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 检查验证码
    # 获取验证码
    redis_store = redis.Redis(connection_pool=pool)
    # 获取redis中的验证码
    code = redis_store.get('validateCode2:%s' % phoneNumber)
    # 检查验证码是否发送
    if not code:
        return jsonify({'code': 0, 'data': '', 'msg': '请先发送验证码!'})
    # 检查验证码是否超时
    ttlstime = redis_store.ttl('validateCode2:%s' % phoneNumber)
    if ttlstime == -2:
        return jsonify({'code': 0, 'data': '', 'msg': '验证码已失效'})
    # 检查验证码是否正确
    if validate_number.upper() != code.decode('utf-8').upper():
        return jsonify({'code': 0, 'data': '', 'msg': '验证码错误'})
    # 检查用户是否存在
    res = jys_db.selectone('select * from bf_user  where mobile=%d ' % int(phoneNumber))
    if res:
        token = gen_token(res['id'])
        result_json = jsonify({'code': 1, 'data': '', 'msg': '登陆成功'})
        resp = make_response(result_json)
        # 更新登录时间
        t = int(time.time())
        sql = 'update df_user set `login_time`={} where id={};'.format(t, int(res['id']))
        jys_db.execute(sql)
        # 设置cookie过期时间
        expires = time.time() + 60 * 60 * 24 * 31
        resp.set_cookie('token', token, expires=expires)
        session['id'] = res['id']
        session['username'] = res['username']
        session['mobile'] = res['mobile']
        redis_store.delete('validateCode2')
        return jsonify({'code': 1, 'data': {'token': 0}, 'msg': '登录成功'})
    else:
        return jsonify({'code': 0, 'data': {'token': 0}, 'msg': '该手机号没有注册'})


# 注销
@users.route('/logout/', methods=['POST'])
def logout():
    resp = make_response(jsonify({'code': 1, 'data': {}, 'msg': '退出成功'}))
    session.pop('id', None)
    resp.delete_cookie('token')
    return resp


# 重置密码
@users.route('/change_password/', methods=['POST'])
def change_password():
    validate_number = request.form.get('validate_number')
    phoneNumber = request.form.get('phone')
    passwd = request.form.get('passwd')
    # 检查数据是否为空
    if not phoneNumber or not validate_number or not passwd:
        return jsonify({'code': 0, 'data': '', 'msg': '请输入手机号码'})
    # 检查手机号
    if not phone_validatte(phoneNumber):
        return jsonify({'code': 0, 'data': '', 'msg': '请输入正确的手机号码'})
    # 检查验证码
    redis_store = redis.Redis(connection_pool=pool)
    validate_number_in_redis = redis_store.get('validateCode2:%s' % phoneNumber)
    ttlstime = redis_store.ttl('validateCode2:%s' % phoneNumber)
    # 检查验证码是否发送
    if not validate_number_in_redis:
        return jsonify({'code': 0, 'data': '', 'msg': '该用户没有发送验证码,请先发送验证码!'})
    # 检查验证码是否有效
    elif ttlstime == -2:
        return jsonify({'code': 0, 'data': {'ttlstime': ttlstime}, 'msg': '验证码已失效'})
    # 检查验证码是否正确
    elif int(validate_number) != int(validate_number_in_redis):
        return jsonify({'code': 0, 'data': {'ttlstime': ttlstime}, 'msg': '验证失败'})
    else:
        # 更新密码
        passwd = hash(passwd)
        sql = 'update  bf_user set `password`="%s" where mobile=%d;' % (passwd, int(phoneNumber))
        jys_db.execute(sql)
        # 缓存中删除验证码
        redis_store.delete('validateCode2:%s' % phoneNumber)
        # 注销用户
        session.pop('id', None)
        resp = jsonify({'code': 1, 'data': '', 'msg': '更改密码成功'})
        resp.delete_cookie('token')
        return resp


'''

以上接口为交接过的接口

'''


# 设置交易密码
@users.route('/set_pay_password/', methods=['GET', 'POST'])
def set_pay_password():
    if request.method == 'POST':
        validate_number = request.form.get('validate_number')
        phoneNumber = request.form.get('phone')
        passwd = request.form.get('passwd')
    else:
        validate_number = request.args.get('validate_number')
        phoneNumber = request.args.get('phone')
        passwd = request.args.get('passwd')
    # 是否发送过验证码
    redis_store = redis.Redis(connection_pool=pool)
    validate_number_in_redis = redis_store.get('validateCode:%s' % phoneNumber)
    ttlstime = redis_store.ttl('validateCode:%s' % phoneNumber)
    if not validate_number_in_redis:
        return jsonify({'code': 0, 'data': '', 'msg': '请先发送验证码!'})
    # 是否超时
    elif ttlstime == -2:
        return jsonify({'code': 0, 'data': {'ttlstime': ttlstime}, 'msg': '验证码已失效'})
    # 验证码是否正确
    elif int(validate_number) != int(validate_number_in_redis):
        return jsonify({'code': 0, 'data': {'ttlstime': ttlstime}, 'msg': '验证失败'})
    else:
        # 哈希密码
        passwd = hash(passwd)
        t = int(time.time())
        sql = 'update  bf_user set `paypassword`="%s" where mobile=%d;' % (passwd, int(phoneNumber))
        jys_db.execute(sql)
        return jsonify({'code': 1, 'data': {'token': ttlstime}, 'msg': '设置密码成功'})


# 修改交易密码
@users.route('/change_pay_password/', methods=['POST'])
def change_pay_password():
    token = request.cookies.get('token')
    if token:
        if check_activate_token(token) == session['id']:
            user_id = check_activate_token(token)
            passwd = request.form.get('passwd')
            jys = jys_db.cursor()
            # 哈希密码
            passwd = hash(passwd)
            t = int(time.time())
            sql = 'update  bf_user set `paypassword`="%s" where user_id=%d;' % (passwd, user_id)
            jys_db.execute(sql)
            return jsonify({'code': 1, 'reulst': '', 'msg': '更改密码成功'})
        else:
            return jsonify({'code': 1, 'data': '', 'msg': '用户未登录,请先登录'})
    else:
        return jsonify({'code': 1, 'data': '', 'msg': '用户未登录,请先登录'})
